package hk.m4s.lr.repair.test.ui.user;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import framework.common.Constant;
import framework.common.baseui.UeBaseActivity;
import framework.common.takephoto.CustomHelper;
import framework.common.widgets.dialogs.UeDialog;
import framework.common.zanetwork.core.ResponseCallback;
import framework.common.zanetwork.core.UploadCallback;
import framework.common.zanetwork.core.UploadHelper;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.ImageModle;
import hk.m4s.lr.repair.test.model.ReturnMoneyModel;
import hk.m4s.lr.repair.test.ui.adapter.GridViewAdapter;
import hk.m4s.lr.repair.test.ui.adapter.ReturnMoneyAdapter;
import hk.m4s.lr.repair.test.utils.CustomerAlertDialog;
import hk.m4s.lr.repair.test.utils.ToastUtil;
import hk.m4s.lr.repair.test.views.InnerGridView;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/3/23.
 * 申请售后
 */

public class TuiMoneyActivity extends UeBaseActivity implements AdapterView.OnItemClickListener{
    private RelativeLayout show_layout;
    private EditText add_en;
    private TextView btn_cancle,btn_sure,user_repair,user_price,user_mo_price,user_dixianprice,user_mo_diprice,backMoneyBtn,backGoodsOrMoneyBtn,takeGoodsBtn;
    private ListView jiangli_list;
    // 图片 九宫格
    private InnerGridView gv;
    // 图片 九宫格适配器
    private GridViewAdapter gvAdapter;

    // 用于保存图片资源文件
    private List<Bitmap> lists = new ArrayList<Bitmap>();
    private ArrayList<TImage> imgList;
    // 用于保存图片路径
    private List<ImageModle> imgs = new ArrayList<ImageModle>();
    // 拍照
    public static final int IMAGE_CAPTURE = 1;
    // 从相册选择
    public static final int IMAGE_SELECT = 2;
    // 照片缩小比例
    private static final int SCALE = 5;
    private List<ReturnMoneyModel.ListBean> jiangliList=new ArrayList<>();
    private ReturnMoneyAdapter jiangliListAdapter;
    private Context context;
    private String selectName="";
    private String orderId;
    private int state=1;
    String type;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_tui_money);
        hiddenFooter();
        showGoBackBtn();
        context=this;
        setTitleText("售后服务");
        orderId=getIntent().getStringExtra("orderId");
        initView();

    }
    public void initView() {
        show_layout= (RelativeLayout) findViewById(R.id.show_layout);
        add_en=(EditText) findViewById(R.id.add_en);
        gv= (InnerGridView) findViewById(R.id.noScrollgridview);
        btn_cancle= (TextView) findViewById(R.id.btn_cancle);
        btn_sure= (TextView) findViewById(R.id.btn_sure);
        user_price= (TextView) findViewById(R.id.user_price);
        user_mo_price= (TextView) findViewById(R.id.user_mo_price);
        user_dixianprice= (TextView) findViewById(R.id.user_dixianprice);
        user_mo_diprice= (TextView) findViewById(R.id.user_mo_diprice);
        user_repair= (TextView) findViewById(R.id.user_repair);
        backMoneyBtn= (TextView) findViewById(R.id.backMoneyBtn);
        backGoodsOrMoneyBtn= (TextView) findViewById(R.id.backGoodsOrMoneyBtn);
        takeGoodsBtn= (TextView) findViewById(R.id.takeGoodsBtn);
        jiangli_list= (ListView) findViewById(R.id.jiangli_list);
        gvAdapter = new GridViewAdapter(this, imgs,"2");
        type=getIntent().getStringExtra("type");
        chageBtn(type);
        gv.setOnItemClickListener(this);
        gv.setAdapter(gvAdapter);
        gvAdapter.setList(imgs);
       // findGoodsReturnMoney();
        jiangliListAdapter=new ReturnMoneyAdapter(context,jiangliList);
        jiangli_list.setAdapter(jiangliListAdapter);
    }
    public void onClick(View view){
        switch (view.getId()){
            case R.id.click_repair:
                show_layout.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_cancle:
                show_layout.setVisibility(View.GONE);
                selectName="";
                break;
            case R.id.btn_sure:
                show_layout.setVisibility(View.GONE);
                for(ReturnMoneyModel.ListBean model:jiangliList){
                    if(model.getState().equals("1")){
                        selectName=model.getText();
                    }
                }
                user_repair.setText(selectName);
                break;
            case R.id.home_send_order:
                if(selectName.equals("")){
                    ToastUtil.toast(context,"请选择退款原因");
                    return;
                }
                //ReturnInsert();
                break;
            case R.id.backMoneyBtn:
                state=1;
                chageBtn("1");
                break;
            case R.id.backGoodsOrMoneyBtn:
                state=2;
                chageBtn("2");
                break;
            case R.id.takeGoodsBtn:
                state=3;
                chageBtn("3");
                break;
        }
    }

//    public void findGoodsReturnMoney() {
//        Map<String, Object> parmas = new HashMap<>();
//        parmas.put("device_type", Constant.device_type);
//        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
//        parmas.put("userId", SharedPreferencesUtils.getSharedPreferences(Constant.userId, ""));
//        parmas.put("orderId", orderId);
//        MyService.findGoodsReturnMoney(context, parmas, new ResponseCallback<ReturnMoneyModel>() {
//            @Override
//            public void onSuccess(ReturnMoneyModel orderDetailModel) {
//                user_price.setText(MoneyTool.getLocalMoney(orderDetailModel.getMoney()));
//                user_dixianprice.setText(MoneyTool.getLocalMoney(orderDetailModel.getAwardMoney()));
//                user_mo_price.setText(orderDetailModel.getMoneyText());
//                user_mo_diprice.setText(orderDetailModel.getAwardMoneyText());
//                   if(orderDetailModel.getList()!=null){
//                       jiangliList.addAll(orderDetailModel.getList());
//                       jiangliListAdapter.notifyDataSetChanged();
//                   }
//            }
//
//            @Override
//            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
//
//            }
//        });
//    }
//    public void ReturnInsert() {
//        Map<String, Object> parmas = new HashMap<>();
//        parmas.put("device_type", Constant.device_type);
//        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
//        parmas.put("userId", SharedPreferencesUtils.getSharedPreferences(Constant.userId, ""));
//        parmas.put("orderId", orderId);
//        parmas.put("type", "1");
//        parmas.put("cause", selectName);
//        if(!add_en.getText().toString().equals("")) {
//            parmas.put("explains", add_en.getText().toString());
//        }
//        if(imgs.size()>0) {
//            try {
//                StringBuffer array=new StringBuffer();
//                for (int i = 0; i < imgs.size(); i++) {
//                    ImageModle model =imgs.get(i);
//                    array.append(model.getUrl()+ ",");
//                }
//                parmas.put("img",array.substring(0, array.length() - 1));
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }
//        MyService.ReturnInsert(context, parmas, new ResponseCallback<ReturnMoneyModel>() {
//            @Override
//            public void onSuccess(ReturnMoneyModel orderDetailModel) {
//               finish();
//            }
//
//            @Override
//            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
//
//            }
//        });
//    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position,
                            long id) {
        if (position == getDataSize()) {// 点击“+”号位置添加图片
            if(imgs.size()==3){
                ToastUtil.toast(context,"最大允许3张");
            }else {
                CustomerAlertDialog.showAlertDialog(TuiMoneyActivity.this, false, "提示", new String[]{"拍照", "从图库选择", "取消"},
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which + 1) {
                                    case 1:// 拍照
                                        CustomHelper.onClick(getTakePhoto(), 0);
                                        dialog.dismiss();
                                        break;
                                    case 2:// 从图库选择
                                        int num = 3 - imgs.size();

                                        if (num > 0) {
                                            CustomHelper.onClick(getTakePhoto(), 1);
                                        }
                                        dialog.dismiss();
                                        break;
                                    case 3:// 取消
                                        dialog.dismiss();
                                        break;

                                    default:
                                        break;
                                }
                            }
                        });
            }
        } else {// 点击图片删除
            CustomerAlertDialog.showAlertDialog(TuiMoneyActivity.this,"提示", "是否删除此图片？", "确定", "取消", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //lists.remove(position);
                    //FileUtils.delFile(list_path.get(position));
                    imgs.remove(position-1);
                    gvAdapter.setList(imgs);
                    dialog.dismiss();
                }
            }, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }
    }
    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        Message msg=new Message();
        msg.obj=result.getImages();
        handler.sendMessage(msg);


    }
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            imgList = (ArrayList<TImage>) msg.obj;
            if(imgList!=null) {
                new UploadHelper().asyncPutObjectFromLocalFile(context, Constant.endpoint, imgList.get(0).getCompressPath(), new UploadCallback<Integer>() {
                    @Override
                    public void onRequestBefore() {
                        UeDialog.showprogressDialog(context,"","上传中...",false);
                    }

                    @Override
                    public void onFailure(PutObjectRequest response, String failureMsg, int code) {
                        UeDialog.hideProgress();
                    }

                    @Override
                    public void onSuccess(PutObjectRequest response, Integer o) {
                        UeDialog.hideProgress();
                        if (o == 200) {
                            String logo = "https://" + Constant.testBucket + ".oss-cn-beijing.aliyuncs.com" + "/" +response.getObjectKey();
                            ImageModle modle=new ImageModle();
                            modle.setUrl(logo);
                            imgs.add(modle);
                            if(imgs!=null){
                                gv.setAdapter(gvAdapter);
                                gvAdapter.setList(imgs);
                            }
                        }
                    }

                    @Override
                    public void onError(PutObjectRequest response, int errorCode, Exception e) {

                    }
                });
            }
        }
    };
    private int getDataSize() {
        return imgs.size() == 0 ? 0 : imgs.size();
    }


    public void chageBtn(String type){
        if(type!=null) {
            if (type.equals("1")) {
                state = 1;
                backMoneyBtn.setBackgroundResource(R.drawable.btn_lowblue_backroud);
                backMoneyBtn.setTextColor(Color.parseColor("#ffffff"));
                backGoodsOrMoneyBtn.setBackgroundResource(R.drawable.btn_gray_backrouds);
                backGoodsOrMoneyBtn.setTextColor(Color.parseColor("#777777"));
                takeGoodsBtn.setBackgroundResource(R.drawable.btn_gray_backrouds);
                takeGoodsBtn.setTextColor(Color.parseColor("#777777"));
            } else if (type.equals("2")) {
                state = 2;
                backGoodsOrMoneyBtn.setBackgroundResource(R.drawable.btn_lowblue_backroud);
                backGoodsOrMoneyBtn.setTextColor(Color.parseColor("#ffffff"));
                backMoneyBtn.setBackgroundResource(R.drawable.btn_gray_backrouds);
                backMoneyBtn.setTextColor(Color.parseColor("#777777"));
                takeGoodsBtn.setBackgroundResource(R.drawable.btn_gray_backrouds);
                takeGoodsBtn.setTextColor(Color.parseColor("#777777"));
            } else {
                state = 3;
                takeGoodsBtn.setBackgroundResource(R.drawable.btn_lowblue_backroud);
                takeGoodsBtn.setTextColor(Color.parseColor("#ffffff"));
                backGoodsOrMoneyBtn.setBackgroundResource(R.drawable.btn_gray_backrouds);
                backGoodsOrMoneyBtn.setTextColor(Color.parseColor("#777777"));
                backMoneyBtn.setBackgroundResource(R.drawable.btn_gray_backrouds);
                backMoneyBtn.setTextColor(Color.parseColor("#777777"));
            }
        }
    }

}
